<?
function prt($array = array()) {
	echo '<pre>';
	print_r($array);
	echo '<pre>';
	exit();
}

function echox($value){
	echo $value;
	exit();
}
class FunctionLib{
	static $check_uri = false;

	/*-------------------------------------------------------------------------*/
	// Sets a cookie, abstract layer allows us to do some checking, etc
	/*-------------------------------------------------------------------------*/
	static function my_setcookie($name, $value = "", $expires=""){
		$expires = ($expires)? $expires : time() + 60*60*24*365;

		setcookie($name, $value, $expires,"/");
		$_COOKIE[$name] = $value;
	}
	static function plainText($str){
		$arr_replace=array(
							'/\<p (.+?)\>(.+?)\<\/p\>/is'		=>	'$2'.' ',
							'/\<br \/\>/is'						=>  ' ',
							'/\<br\>/is'						=>  ' '
							);

		$str = preg_replace(array_keys($arr_replace),$arr_replace,$str);
		$str = strip_tags($str);

		//$filter = "\$|,,|@|\!|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\$|\.";
		//$filter = "\$|,,|@|\!|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\$|\.\.";
		//$str = preg_replace("/$filter/is", " ", $str);

		return self::delDoubleSpace(self::trimSpace(str_replace(array(chr(13),chr(9),chr(10),chr(239))," ",$str)));
	}

	static function _name_cleaner($name,$replace_string="_"){
		return preg_replace( "/[^a-zA-Z0-9\-\_]/", $replace_string , $name );
	}

	static function make_safe_name($name,$replace_string="_"){
		return preg_replace( "/[^\w\.]/", $replace_string , $name );
	}

	static function convertUnicodeCase($test){
		$uppercase_utf8=array("A","Á","À","Ả","Ã","Ạ","Â","Ấ","Ầ","Ẩ","Ẫ","Ậ","Ă","Ắ","Ằ","Ẳ","Ẵ","Ặ","E","É","È","Ẻ","Ẽ","Ẹ","Ê","Ế","Ề","Ể","Ễ","Ệ","I","Í","Ì","Ỉ","Ĩ","Ị","O","Ó","Ò","Ỏ","Õ","Ọ","Ô","Ố","Ồ","Ổ","Ỗ","Ộ","Ơ","Ớ","Ờ","Ở","Ỡ","Ợ","U","Ú","Ù","Ủ","Ũ","Ụ","Ư","Ứ","Ừ","Ử","Ữ","Ự","Y","Ý","Ỳ","Ỷ","Ỹ","Ỵ","Đ"," ", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+", "=", "|", "\\", "{", "}",":", ";", "<", ">", "/", "?");
		$lowercase_utf8=array("a","á","à","ả","ã","ạ","â","ấ","ầ","ẩ","ẫ","ậ","ă","ắ","ằ","ẳ","ẵ","ặ","e","é","è","ẻ","ẽ","ẹ","ê","ế","ề","ể","ễ","ệ","i","í","ì","ỉ","ĩ","ị","o","ó","ò","ỏ","õ","ọ","ô","ố","ồ","ổ","ỗ","ộ","ơ","ớ","ờ","ở","ỡ","ợ","u","ú","ù","ủ","ũ","ụ","ư","ứ","ừ","ử","ữ","ự","y","ý","ỳ","ỷ","ỹ","ỵ","đ","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", "", "", "", "", "");
		if(!$test){
			return $test;
		} else {
			$new_test=str_replace($uppercase_utf8,$lowercase_utf8,$test);
			return $new_test;
		}
	}
	static function filter_title($str){
		$str = FunctionLib::post_db_parse_html($str);
		//$filter = "\$|,,|@|\!|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\$|\.\.";
		$filter = "\$|,,|@|\!|#|~|`|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\'|\"|\<|\>|\?|\||\\|\$|\.\.";
		return preg_replace("/$filter/is", " ", $str);
	}

	static function convertUnicodeCaseWithoutHtml($test){
		$uppercase_utf8=array("A","Á","À","Ả","Ã","Ạ","Â","Ấ","Ầ","Ẩ","Ẫ","Ậ","Ă","Ắ","Ằ","Ẳ","Ẵ","Ặ","E","É","È","Ẻ","Ẽ","Ẹ","Ê","Ế","Ề","Ể","Ễ","Ệ","I","Í","Ì","Ỉ","Ĩ","Ị","O","Ó","Ò","Ỏ","Õ","Ọ","Ô","Ố","Ồ","Ổ","Ỗ","Ộ","Ơ","Ớ","Ờ","Ở","Ỡ","Ợ","U","Ú","Ù","Ủ","Ũ","Ụ","Ư","Ứ","Ừ","Ử","Ữ","Ự","Y","Ý","Ỳ","Ỷ","Ỹ","Ỵ","Đ","Q","W","R","T","U","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M","P");
		$lowercase_utf8=array("a","á","à","ả","ã","ạ","â","ấ","ầ","ẩ","ẫ","ậ","ă","ắ","ằ","ẳ","ẵ","ặ","e","é","è","ẻ","ẽ","ẹ","ê","ế","ề","ể","ễ","ệ","i","í","ì","ỉ","ĩ","ị","o","ó","ò","ỏ","õ","ọ","ô","ố","ồ","ổ","ỗ","ộ","ơ","ớ","ờ","ở","ỡ","ợ","u","ú","ù","ủ","ũ","ụ","ư","ứ","ừ","ử","ữ","ự","y","ý","ỳ","ỷ","ỹ","ỵ","đ","q","w","r","t","p","s","d","f","g","h","j","k","l","z","x","c","v","b","n","m","p");
		if(!$test){
			return $test;
		} else {
			$new_test=str_replace($uppercase_utf8,$lowercase_utf8,$test);
			return $new_test;
		}
	}

	static function safe_title($text){
		$text = FunctionLib::post_db_parse_html($text);
		$text = self::stripUnicode($text);
		$text = self::_name_cleaner($text,"-");
		$text = str_replace("----","-",$text);
		$text = str_replace("---","-",$text);
		$text = str_replace("--","-",$text);
		$text = trim($text, '-');

		if($text){
			return $text;
		}
		else{
			return "shop";
		}
	}

	static function stripUnicode($str){
		if(!$str) return false;
		$marTViet=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
		"ằ","ắ","ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề"
		,"ế","ệ","ể","ễ",
		"ì","í","ị","ỉ","ĩ",
		"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
		,"ờ","ớ","ợ","ở","ỡ",
		"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
		"ỳ","ý","ỵ","ỷ","ỹ",
		"đ",
		"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
		,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
		"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
		"Ì","Í","Ị","Ỉ","Ĩ",
		"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
		,"Ờ","Ớ","Ợ","Ở","Ỡ",
		"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
		"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
		"Đ");

		$marKoDau=array("a","a","a","a","a","a","a","a","a","a","a"
		,"a","a","a","a","a","a",
		"e","e","e","e","e","e","e","e","e","e","e",
		"i","i","i","i","i",
		"o","o","o","o","o","o","o","o","o","o","o","o"
		,"o","o","o","o","o",
		"u","u","u","u","u","u","u","u","u","u","u",
		"y","y","y","y","y",
		"d",
		"A","A","A","A","A","A","A","A","A","A","A","A"
		,"A","A","A","A","A",
		"E","E","E","E","E","E","E","E","E","E","E",
		"I","I","I","I","I",
		"O","O","O","O","O","O","O","O","O","O","O","O"
		,"O","O","O","O","O",
		"U","U","U","U","U","U","U","U","U","U","U",
		"Y","Y","Y","Y","Y",
		"D");

		$str = str_replace($marTViet,$marKoDau,$str);
		return $str;
	}

	static function getExtension($file) {
		$pos = strrpos($file, '.');
		if(!$pos) {
			return false;
		}
		$str = substr($file, $pos, strlen($file));
		return strtolower($str);
	}


	static function getParam($aVarName,$aVarAlt=""){
		$lVarName=@$_REQUEST[$aVarName];
		if (!Empty($lVarName)){
			if (is_array($lVarName)){
				$lReturnArray = array();
				foreach ($lVarName as $key => $value) {
					$value = self::clean_value($value);
					$key = self::clean_key($key);
					$lReturnArray[$key]=$value;
				}
				return $lReturnArray;
			}
			else
			return self::clean_value($lVarName); // Clean input and return it

		}
		else
		return $aVarAlt;
	}

	static function cleanHtml($aVarName,$aVarAlt=""){
		$lVarName=$aVarName;
		if (!Empty($lVarName)){
			if (is_array($lVarName)){
				$lReturnArray = array();
				foreach ($lVarName as $key => $value) {
					$value = self::clean_value($value);
					$key = self::clean_key($key);
					$lReturnArray[$key]=$value;
				}
				return $lReturnArray;
			}
			else
			return self::clean_value($lVarName); // Clean input and return it

		}
		else
		return $aVarAlt;
	}

	function getParamInt($aVarName,$aVarAlt=0){
		$lNum = 0;
		if ($aVarName){
			if (isset($_POST[$aVarName]))
				$lNum = $_POST[$aVarName];
			elseif (isset($_GET[$aVarName]))
				$lNum = $_GET[$aVarName];
			else
				$lNum = $aVarAlt;
		}

		return (int)$lNum;
		//return (int)preg_replace('/\D+/', '', $lNum);
	}

	/*-------------------------------------------------------------------------*/
	// Key Cleaner - ensures no funny business with form elements
	/*-------------------------------------------------------------------------*/
	static function clean_key($key){
		if ($key == ""){
			return "";
		}

		$key = htmlspecialchars(urldecode($key));
		$key = preg_replace( "/\.\./"           , ""  , $key );
		$key = preg_replace( "/\_\_(.+?)\_\_/"  , ""  , $key );
		$key = preg_replace( "/^([\w\.\-\_]+)$/", "$1", $key );
		return $key;
	}

	/*-------------------------------------------------------------------------*/
	// Clean value
	/*-------------------------------------------------------------------------*/

	static function clean_value($val){
		$strip_space_chr = 1;
		$get_magic_quotes = @get_magic_quotes_gpc();

		if ($val == ""){
			return "";
		}

		$val = str_replace( "&#032;", " ", $val );

		if ( $strip_space_chr ){
			$val = str_replace( chr(0xCA), "", $val );  //Remove sneaky spaces
		}
		//$val = str_replace( "&"            , "&amp;"         , $val );
		$val = str_replace( "<!--"         , ""  , $val ); //&#60;&#33;--
		$val = str_replace( "-->"          , ""       , $val ); //--&#62;
		$val = preg_replace( "/<script/i"  , "&#60;script"   , $val );
		$val = str_replace( ">"            , "&gt;"          , $val );
		$val = str_replace( "<"            , "&lt;"          , $val );
		$val = str_replace( "\""           , "&quot;"        , $val );
		//$val = preg_replace( "/\n/"        , "<br />"        , $val ); // Convert literal newlines
		$val = preg_replace( "/\\\$/"      , "&#036;"        , $val );
		$val = preg_replace( "/\r/"        , ""              , $val ); // Remove literal carriage returns
		$val = str_replace( "!"            , "&#33;"         , $val );
		$val = str_replace( "'"            , "&#39;"         , $val ); // IMPORTANT: It helps to increase sql query safety.

		if ( $get_magic_quotes ){
			$val = stripslashes($val);
		}

		$val = preg_replace( "/\\\(?!&amp;#|\?#)/", "&#092;", $val );

		return $val;
	}

	//-----------------------------------------
	// parse_html
	// Converts the doHTML tag
	//-----------------------------------------
	static function post_db_parse_html($t=""){
		if ( $t == "" ){
			return $t;
		}

		//-----------------------------------------
		// Remove <br>s 'cos we know they can't
		// be user inputted, 'cos they are still
		// &lt;br&gt; at this point :)
		//-----------------------------------------

		/*		if ( $this->pp_nl2br != 1 )
		{
		$t = str_replace( "<br>"    , "\n" , $t );
		$t = str_replace( "<br />"  , "\n" , $t );
		}*/

		$t = str_replace( "&#39;"   , "'", $t );
		$t = str_replace( "&#33;"   , "!", $t );
		$t = str_replace( "&#036;"  , "$", $t );
		$t = str_replace( "&#124;"  , "|", $t );
		$t = str_replace( "&amp;"   , "&", $t );
		$t = str_replace( "&gt;"    , ">", $t );
		$t = str_replace( "&lt;"    , "<", $t );
		$t = str_replace( "&quot;"  , '"', $t );

		//-----------------------------------------
		// Take a crack at parsing some of the nasties
		// NOTE: THIS IS NOT DESIGNED AS A FOOLPROOF METHOD
		// AND SHOULD NOT BE RELIED UPON!
		//-----------------------------------------

		$t = preg_replace( "/javascript/i" , "j&#097;v&#097;script", $t );
		$t = preg_replace( "/alert/i"      , "&#097;lert"          , $t );
		$t = preg_replace( "/about:/i"     , "&#097;bout:"         , $t );
		$t = preg_replace( "/onmouseover/i", "&#111;nmouseover"    , $t );
		$t = preg_replace( "/onmouseout/i", "&#111;nmouseout"    , $t );
		$t = preg_replace( "/onclick/i"    , "&#111;nclick"        , $t );
		$t = preg_replace( "/onload/i"     , "&#111;nload"         , $t );
		$t = preg_replace( "/onsubmit/i"   , "&#111;nsubmit"       , $t );
		//$t = preg_replace( "/object/i"   , "&#111;bject"       , $t );
		$t = preg_replace( "/frame/i"   , "fr&#097;me"       , $t );
		$t = preg_replace( "/applet/i"   , "&#097;pplet"       , $t );
		$t = preg_replace( "/meta/i"   , "met&#097;"       , $t );
		//$t = preg_replace( "/embed/i"   , "met&#097;"       , $t );

		return $t;
	}

	static function make_single_space($t=""){
		return ($t=="") ? $t : preg_replace("#[[:space:]]+#", " ", $t);
	}

	static function CheckDir($pDir){
		if (is_dir($pDir))
		return true;
		if (!@mkdir($pDir,0777,true)){
			return false;
		}
		self::chmod_dir($pDir,0777);
		return true;
	}

	static function chmod_dir($dir,$mod=0777){
		$parent_dir=dirname(str_replace(ROOT_PATH,'',$dir));
		if($parent_dir!='' && $parent_dir!='.'){
			//echo $parent_dir.'/<br />';
			@chmod($dir,$mod);
			self::chmod_dir($parent_dir,$mod);
		}
		return true;
	}
	static function trimSpace($str=""){
		if($str==""){
			return;
		}
		$str = str_replace("&nbsp;", " ", $str);
		$str = preg_replace('![\t ]*[\r\n]+[\t ]*!', ' ', $str);
		return trim(eregi_replace("[[:space:]]+", " ", trim($str)));
	}

	static function delDoubleSpace($str){
		if (eregi('  ',$str)){
			$str = eregi_replace('  ',' ',$str);
			$str = self::delDoubleSpace($str);
			return $str;
		}
		else{
			return $str;
		}
	}
//get real IP - by TuanNV - 26/09/08
	static function ip_first($ips) {
	  if (($pos = strpos($ips, ',')) != false) {
	    return substr($ips, 0, $pos);
	  } else {
	    return $ips;
	  }
	}
	static function ip_valid($ips) {
	  if (isset($ips)) {
	    $ip    = self::ip_first($ips);
	    $ipnum = ip2long($ip);
	    if ($ipnum !== -1 && $ipnum !== false && (long2ip($ipnum) === $ip)) { // PHP 4 and PHP 5
	      if (($ipnum < 167772160   || $ipnum >   184549375) && // Not in 10.0.0.0/8
	          ($ipnum < -1408237568 || $ipnum > -1407188993) && // Not in 172.16.0.0/12
	          ($ipnum < -1062731776 || $ipnum > -1062666241))   // Not in 192.168.0.0/16
	        return true;
	    }
	  }
	  return false;
	}

	static function ip() {
	  $check = array('HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED',
	                 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED',
	                 'HTTP_VIA', 'HTTP_X_COMING_FROM', 'HTTP_COMING_FROM');
	  foreach ($check as $c) {
	    //if (self::ip_valid(&$_SERVER[$c])) {
	    if (isset($_SERVER[$c]) && self::ip_valid($_SERVER[$c])) {
	      return self::ip_first($_SERVER[$c]);
	    }
	  }

	  return $_SERVER['REMOTE_ADDR'];
	}

	static function session_started(){
	     if(isset($_SESSION)){ return true; }else{ return false; }
	}
	static function empty_dir($name)
	{
		if($dir = @opendir($name)){
			while($file=readdir($dir)){
				if($file!='..'){
					@unlink($file);
				}
			}
			closedir($dir);
		}
	}

	static function empty_all_dir($name, $remove_sub_dir = false,$remove_self=false){
		if(is_dir($name)){
			if($dir = opendir($name)){
				$dirs = array();
				while($file=readdir($dir)){
					if($file!='..' and $file!='.'){
						if(is_dir($name.'/'.$file)){
							$dirs[]=$file;
						}
						else{
							@unlink($name.'/'.$file);
						}
					}
				}
				closedir($dir);
				foreach($dirs as $dir_){
					if($remove_self || $remove_sub_dir)
						self::empty_all_dir($name.'/'.$dir_, true,true);
					else
						self::empty_all_dir($name.'/'.$dir_, false,false);
				}

				if($remove_self){
					@rmdir($name);
				}
			}
		}
	}
	
	//for json
	static function JsonErr($msg = '', $mixed = array()){
		$arr = array('err' => -1, 'msg' => $msg);
		if(!empty($mixed)){
			$arr = $arr + $mixed;
		}
		return json_encode($arr);
	}
	static function JsonSuccess($msg, $mixed = array()){
		$arr = array('err' => 0, 'msg' => $msg);
		if(!empty($mixed)){
			$arr = $arr + $mixed;
		}
		return json_encode($arr);
	}

	static function priceFormat($price,$currency = ''){
		$currency = ($currency) ? $currency : CGlobal::$currency;
		if($price){
			$currency=" ".$currency;
			if(stripos($price, '.') !== false)
				return $price.$currency;
			else
				return number_format($price,0,',','.').$currency;
		}
		return "0 $currency";
	}
	static function dateFormat($time, $format = 'd/m - H:i'){
		$time = $time ? $time : TIME_NOW;
		return date($format,$time);
	}
	//clean & valid url
	static function convertURL($link = ''){
		$http = (preg_match_all("#^(http\:\/\/)#", $link) > 0) ? '' : 'http://';
		return $http.$link;
	}

	//hidden uid
	static function hiddenID($id = 0, $decode = false){
		if($decode){
			$id = (1984 - 13*12) + $id;
		}else{
			$id = (13*12 - 1984) + $id;
		}
		return $id;
	}

	static function checkReferIp($order_id = 0, $refer = 0, $check_ip = false, $status = 1){
		$row = array();
		if($refer > 0 || $order_id > 0){
			$ip = FunctionLib::ip();
			$where = '';
			if($check_ip){
				$where = ' AND ip = "'.$ip.'"';
			}
			if($order_id){
				$where .= ' AND order_id = "'.$order_id.'"';
			}
			if($refer){
				$where .= ' AND customer_id = "'.$refer.'"';
			}
			$row = DB::fetch("SELECT * FROM ". T_REFER. " WHERE status = $status $where");
		}
		return (!empty($row)) ? $row : false;
	}

	static function FacebookTimeFormat($date)
	{
		if(empty($date)) {
			return "No date provided";
		}
		
		$periods         = array('giây','phút','giờ','ngày','tuần','tháng','năm','thập kỷ');
		$lengths         = array("60","60","24","7","4.35","12","10");
		
		$now             = TIME_NOW;
		$unix_date         = $date;
		
		// check validity of date
		if(empty($unix_date)) {    
			return "Bad date";
		}
	
		// is it future date or past date
		if($now > $unix_date) {
			$difference     = $now - $unix_date;
			$tense         = "trước";
		} else {
			$difference     = $unix_date - $now;
			$tense         = "from now";
		}
		
		for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
			$difference /= $lengths[$j];
		}
		
		$difference = round($difference);
		
		if($difference != 1) {
			//$periods[$j].= "s";
		}
		
		return "$difference $periods[$j] {$tense}";
	}
}
?>